package org.darkforest.admin.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.codec.digest.DigestUtils;
import org.darkforest.common.services.AdminService;
import org.darkforest.annotation.ControllerLog;
import org.darkforest.model.Admin;
import org.darkforest.vo.MemberBase;
import org.darkforest.vo.WapAjaxMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by valentina on 15/5/9.
 * 登录，主页面等操作控制类
 */
@Controller
public class MainController {

    Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private AdminService adminService;

    /**
     * 首页跳转到登录
     * @return
     */
    @RequestMapping("/")
    public String index(){

        return "redirect:/login";
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 验证注册码
     * @return
     */
    @RequestMapping("checkVerifyCode")
    public @ResponseBody
    boolean checkVerifyCode(HttpServletRequest request){
        String verifyCode = request.getParameter("verifyCode").toLowerCase();
        String randCode = (String)request.getSession().getAttribute("rand");
        if(verifyCode.equals(randCode.toLowerCase())){
            return true;
        }else{
            return false;
        }

    }

    /**
     * 执行登录操作
     * @return
     */

    @RequestMapping(value = "doLogin",method = RequestMethod.POST)
    public String login(@RequestParam String uname,@RequestParam String pwd,@RequestParam String captcha,HttpServletRequest request,String reUrl){
        logger.debug("name:"+uname+",pwd:"+pwd+",captcha:"+captcha);
        WapAjaxMsg<MemberBase> res = adminService.doLogin(uname,pwd);
        logger.debug("user:"+res.getDatas().getUserId()+",error:"+res.getError());
        String url="";
        if(res.getError()==null){
            request.getSession().setAttribute("memInfo", res.getDatas());
             url= (reUrl==null ||"".equals(reUrl.trim()))?"dashboard/main":"dashboard/main?reUrl="+reUrl;
//            modelAndView = new ModelAndView(url);
            // 错误信息清空
            if (request.getSession().getAttribute("msg") != null) {
                request.getSession().removeAttribute("msg");
            }
        }else{
            url = "/login";
            request.getSession().setAttribute("msg",res.getError());
        }
        return "redirect:"+url;
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        //清除用户session数据，跳转到首页
        session.removeAttribute("memInfo");
        session.invalidate();
        return "redirect:/login";
    }

    /**
     * 跳转到修改密码页面
     * @return
     */
    @RequestMapping("main/toModifyPwd")
    public String toModifyPwd(){

        return "modify_pwd";
    }
    @ControllerLog(description ="管理员登录操作")
    @RequestMapping(value = "main/modifyPwd",method = RequestMethod.POST)
    public ModelAndView modifyPwd(String new_pw,HttpSession session){
        Integer memberId = ((MemberBase)session.getAttribute("memInfo")).getUserId();
        Admin vo =  new Admin();
        vo.setAdminId(memberId);
        vo.setAdminPassword(DigestUtils.md5Hex(new_pw));
        adminService.updateByPrimaryKeySelective(vo);
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "密码修改成功，请重新登录");
        modelAndView.addObject("returnUrl", "logout");
       return  modelAndView;
    }

    /**
     * 验证旧密码
     * @return
     */
    @RequestMapping("checkPwd")
    public @ResponseBody boolean checkPwd(String old_pw,HttpSession session) {
        Admin vo =  new Admin();
        Integer adminId = ((MemberBase) session.getAttribute("memInfo")).getUserId();
        vo.setAdminId(adminId);
        Admin member = adminService.getAdminInfoByCondition(vo);
        String oldPwd = DigestUtils.md5Hex(old_pw);
        if (oldPwd.equals(member.getAdminPassword())) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping(value = "downloadFromTmp",method = RequestMethod.GET)
    public ModelAndView downloadFromTmp(HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        InputStream in = null;
        String file = request.getParameter("file");
        String fileName = request.getParameter("filename");
        if (fileName == null || fileName.trim().isEmpty()) {
            fileName = file;
        }

        System.out.println("fileName1="+fileName);
        try {
            String dir = request.getSession().getServletContext().getRealPath("/").concat(File.separator).concat("temp").concat(File.separator);
            in = new FileInputStream(dir + file);
            fileName = URLDecoder.decode(fileName.trim(), "utf8").replaceAll("\\+", "%20");
            System.out.println("fileName2="+fileName);
            String browser = request.getHeader("User-Agent");
            if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
                // IE6, IE7 浏览器
                fileName = "filename=" + new String(fileName.getBytes(), "ISO8859-1");
            } else if (-1 < browser.indexOf("MSIE 8.0")) {
                // IE8, IE9 浏览器
                fileName = "filename=" + URLEncoder.encode(fileName, "UTF-8");
            } else if (-1 < browser.indexOf("Safari")) {
                // 苹果
                fileName = "filename="  + new String(fileName.getBytes(), "ISO8859-1");
            }  else if (-1 < browser.indexOf("Chrome")) {
                // 谷歌
                fileName = "filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 火狐或者其他的浏览器
                fileName = "filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8");
            }
            System.out.println("fileName3="+fileName);
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;" + fileName);

            out = response.getOutputStream();
            byte[] cache = new byte[4096];
            int read = 0;
            while ((read = in.read(cache)) != -1) {
                out.write(cache, 0, read);
                out.flush();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            ModelAndView modelAndView = new ModelAndView("msg");
            modelAndView.addObject("msg", "文件下载出错");
            String returnUrl = request.getParameter("returnUrl");
            returnUrl = returnUrl.replaceAll("_", "/");
            modelAndView.addObject("returnUrl", returnUrl);
            return modelAndView;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
